<template>
  <div class="population-density-out detailedParent">


    <el-select v-model="value" placeholder="选择年份" style="width: 150px;position: absolute;top: 0;left: 0;z-index: 100">
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          :disabled="item.disabled"
      />
    </el-select>

    <el-button @click="autoPlay" style="width: 50px;position: absolute;top: 0;left: 160px;z-index: 100;font-size: 12px">
      {{playText}}
    </el-button>

    <div id="population-density-echarts"></div>

    <el-dialog v-model="dialogVisible" title="图表详情" width="80vw" height="height">
      <div>
        <DetailedPopulationSize></DetailedPopulationSize>
      </div>
    </el-dialog>
    <div class="ranking" id="population-density-rank"></div>

  </div>
</template>

<style scoped>

.population-density-out{
  height: 100%;
  width: 100%;
}

#population-density-echarts{
  height: 100%;
  width: 100%;
}

.ranking{
  border-radius: 5%;

  position: absolute;
  top: 10px;
  right: 20px;
  height: 90%;
  width: 25%;
}
</style>

<script setup>
import {onMounted, ref,watch} from "vue";
import {getPopulationByYear, getPopulationDensityByYear} from "@/api/population.js";
import * as echarts from "echarts";
import chinaMap from "../../../static/map/china.json";
import theme from "../../../static/theme/walden.json";
import axios from "axios";
import DetailedHomeStruct from "@/components/DemographicCharacteristics/detailed/DetailedHomeStruct.vue";
import {useDetailedStore} from "@/store/useDetailedStore.js";
import {detailedPopulationSizeEvent} from "@/consts/eventName.js";
import emitter from "@/utils/emitter.js";
import DetailedPopulationDensity from "@/components/mapData/DetailedPopulationDensity.vue";
import DetailedPopulationSize from "@/components/mapData/DetailedPopulationSize.vue";

let playFlag = false
let playText = ref("开始演示")

let initYear = 2023

let chartDom
let myChart
let option;

let rankChartDom
let rankMyChart
let rankOption;

let options = []
let value = ref('')

let dialogVisible = ref(false)

let detailedStore = useDetailedStore()


for (let i = 2000; i < 2024; i++) {
  options.push({
    value: i,
    label: i+'年',
  })
}

onMounted(()=>{
  getPopulationByYear(initYear).then((value)=>{
    let data = value.data
    let mapData = []

    data.forEach((item)=>{
      const jsonMap = new Map(Object.entries(item));
      mapData.push({
        name:jsonMap.keys().next().value,
        value:jsonMap.values().next().value
      })
    })
    return mapData
  }).then((value)=>{
    let max = 0
    let min = 10000000000

    chartDom = document.getElementById('population-density-echarts');
    myChart = echarts.init(chartDom,theme);
    echarts.registerMap('CHINA',chinaMap)

    value.forEach((item)=>{
      if (item.value > max){
        if (item.name !== "上海市"){
          max = item.value
        }
      }
      if (item.value < min){
        min = item.value
      }
    })

    option = createOption(min,max,value,initYear)

    myChart.setOption(option);

    return value
  }).then((value)=>{
    let yData = []
    let xData = []

    rankChartDom = document.getElementById('population-density-rank');
    rankMyChart = echarts.init(rankChartDom,theme);

    value.sort((a,b)=>{
      return a.value - b.value
    }).forEach((item)=>{
      xData.push(item.value)
      yData.push(item.name)
    })

    rankOption = createRankOption({xData:xData,yData:yData})

    rankMyChart.setOption(rankOption)
  }).then((value)=>{
    myChart.on("click", function (params) {

      dialogVisible.value = true

      if (detailedStore.detailedLoadFlag.get(detailedPopulationSizeEvent)){
        emitter.emit(detailedPopulationSizeEvent,params.data.name)
      }else {
        detailedStore.detailedData.set(detailedPopulationSizeEvent,params.data.name)
      }
    })
  }).catch((reason)=>{

  })
})

watch(value,(newValue)=>{
  if (playFlag){
    alert("请先停止演示")
  }else {
    getData(newValue)
  }
})

function getData(year){
  getPopulationByYear(year).then((value)=>{
    let data = value.data
    let mapData = []

    data.forEach((item)=>{
      const jsonMap = new Map(Object.entries(item));
      mapData.push({
        name:jsonMap.keys().next().value,
        value:jsonMap.values().next().value
      })
    })
    return mapData
  }).then((value)=>{
    let max = 0
    let min = 10000000000

    value.forEach((item)=>{
      if (item.value > max){
        if (item.name !== "上海市"){
          max = item.value
        }
      }
      if (item.value < min){
        min = item.value
      }
    })

    option = createOption(min,max,value,year)

    myChart.setOption(option);

    return value
  }).then((value)=>{
    let yData = []
    let xData = []

    rankChartDom = document.getElementById('population-density-rank');
    rankMyChart = echarts.init(rankChartDom,theme);

    value.sort((a,b)=>{
      return a.value - b.value
    }).forEach((item)=>{
      xData.push(item.value)
      yData.push(item.name)
    })

    rankOption = createRankOption({xData:xData,yData:yData})

    rankMyChart.setOption(rankOption)
  }).catch((reason)=>{

  })
}

function createRankOption(value){
  return option = {
    title:{
      text:"各省排名",
      y:25,
      x:"center",
      textStyle: {
        fontSize:15 // 设置标题字体大小
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },

    xAxis: [
      {
        type: 'value',
        show:false
      },

    ],
    yAxis: [
      {
        type: 'category',
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 0, // 强制显示所有标签，对于 category 类型的轴来说通常是 0 或者不设置

        },
        data: value.yData
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    series: [
      {
        name: '城市',
        type: 'bar',
        label: {
          show: false,
          position: 'inside'
        },
        emphasis: {
          focus: 'series'
        },
        data: value.xData
      }
    ]
  };
}


function createOption(min,max,value,title){
  return  {
    title: {
      text: title+"年-人口数量",
      x:"center",
      y:"10",
      textStyle: { //主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
        fontSize: 25,
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>{c} 人/平方公里'
    },
    series: [
      {
        name: 'China',
        type: 'map',
        map: 'CHINA',
        roam: true,
        zoom:1.5,
        center: [106.114129, 37.550339],
        emphasis: {
          label: {
            show: true
          }
        },
        selectedMode: false,
        label:true,
        data:value,
      }
    ],
    selectedMode: false,
    visualMap: {
      left: 'left',
      min: min,
      max: max,
      inRange: {
        color: [
          '#313695',
          '#4575b4',
          '#74add1',
          '#abd9e9',
          '#e0f3f8',
          '#ffffbf',
          '#fee090',
          '#fdae61',
          '#f46d43',
          '#d73027',
          '#a50026'
        ]
      },
      text: ['High', 'Low'],
      calculable: true
    },
  };
}

let count = 0

function autoPlay(){
  playFlag = !playFlag
  if (playFlag){
    playText.value = "停止演示"
  }else {
    playText.value = "开始演示"
  }
  console.log(playText.value)
}

setInterval(()=>{
  if (playFlag){
    getData(options[count].value)
    count = (count+1)%options.length
  }else {
    count = 0
  }

},500)



</script>